//
//  CLGNetwork.m
//  CLGNetworkApp
//
//  Created by Liu Guocheng on 2018/4/2.
//  Copyright © 2018年 Sumavision. All rights reserved.
//

#import "CLGNetwork.h"

@implementation CLGNetwork

+ (CLGTask *)GET:(NSURL *)url
      parameters:(NSDictionary *)parameters
         headers:(NSDictionary *)headers
         timeout:(NSTimeInterval)timeout
      completion:(CLGNetworkCompletion)completion
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    session.responseSerializer = [AFJSONResponseSerializer serializer];
    session.requestSerializer.timeoutInterval = timeout;
    
    for (NSString *key in headers.allKeys) {
        if ([key isKindOfClass:[NSString class]] && [headers[key] isKindOfClass:[NSString class]]) {
            [session.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
        }
    }
    
    NSURLSessionDataTask * task = [session GET:url.absoluteString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *error;
        
        if (![responseObject isKindOfClass:[NSDictionary class]] && ![responseObject isKindOfClass:[NSArray class]]) {
            responseObject = nil;
            error = [NSError errorWithDomain:@"CLGNetwork" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"Response is not a valid JSON"}];
        }
        
        if (completion) {
            completion(responseObject, error);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (completion) {
            completion(nil, error);
        }
    }];
    
    return task;
}

@end
